import dayjs from "dayjs";
import { myGoodsRateGetList, myGoodsRateReplyComments } from "@/api/modules/goodsRate";
import { myGoodsList, GoodsItemModel } from "@/api/modules/goods";
import type { MyGoodsRateGetListItem } from "@/api/modules/goodsRate";
import { useState, useEffect } from "react";
import { message, Button, Table, Space, Select, Image, Rate, Tooltip, Popover, Input } from "antd";
import { RedoOutlined } from "@ant-design/icons";
import Cimage from "@/components/Cimage";
import { showFullScreenLoading, tryHideFullScreenLoading } from "@/config/serviceLoading";
const { Option } = Select;
const { TextArea } = Input;
interface ListQuery {
	page: number;
	size: number;
	total: number;
	goodsId: number | string | null;
}
const orderAdminComment = () => {
	const [listQuery, setListQuery] = useState<ListQuery>({
		page: 1,
		size: 10,
		total: 0,
		goodsId: null
	});
	const [tableData, setTableData] = useState<MyGoodsRateGetListItem[]>([]);
	const [loading, setLoading] = useState<boolean>(false);
	const [goodsData, setGoodsData] = useState<GoodsItemModel[]>([]);
	// 获取评价列表
	async function getList(listQueryRef: ListQuery) {
		setLoading(true);
		try {
			const { code, data } = await myGoodsRateGetList(listQueryRef);
			if (code === 0) {
				setListQuery({
					...listQueryRef,
					total: data.total
				});
				setTableData(data.list);
			}
		} finally {
			setLoading(false);
		}
	}
	async function getGoodsList() {
		const { code, data } = await myGoodsList({
			page: 1,
			size: 99999
		});
		if (code === 0) {
			setGoodsData(data!.list);
		}
	}
	// 回复评论
	const [popoverVisible, setPopoverVisible] = useState<boolean>(false);
	const [popoverDescription, setPopoverDescription] = useState<string>("");
	async function popoverSubmit(item: MyGoodsRateGetListItem) {
		if (!popoverDescription) {
			message.warning("请输入回复内容再提交！");
			return;
		}
		showFullScreenLoading();
		try {
			const { code, msg } = await myGoodsRateReplyComments({
				parentId: item.id,
				type: "admin",
				userId: item.userId,
				adminId: item.adminId,
				goodsId: item.goodsId,
				description: popoverDescription
			});
			if (code === 0) {
				message.success(msg);
				setPopoverVisible(false);
				setPopoverDescription("");
				// 重新获取列表
				getList(listQuery);
			}
		} finally {
			tryHideFullScreenLoading();
		}
	}
	// 分页器变化回调
	function handleTableChange(pagination: any) {
		const listQueryRef: ListQuery = {
			...listQuery,
			page: pagination.current,
			size: pagination.pageSize,
			total: pagination.total
		};
		setListQuery(listQueryRef);
		getList(listQueryRef);
	}
	function handleSelectChange(value: string) {
		const listQueryRef: ListQuery = {
			...listQuery,
			goodsId: value
		};
		setListQuery(listQueryRef);
		getList(listQueryRef);
	}
	const handleOpenChange = (newOpen: boolean) => {
		setPopoverVisible(newOpen);
	};
	useEffect(() => {
		getList(listQuery);
		getGoodsList();
	}, []);
	// 表格列
	const columns: any[] = [
		{
			title: "评价时间",
			dataIndex: "createTime",
			key: "createTime",
			align: "center",
			ellipsis: {
				showTitle: false
			},
			width: "8%",
			render: (createTime: number) => (
				<Tooltip placement="topLeft" title={dayjs(createTime || new Date()).format("YYYY-MM-DD HH:mm")}>
					{dayjs(createTime || new Date()).format("YYYY-MM-DD HH:mm")}
				</Tooltip>
			)
		},
		{
			title: "订单编号",
			dataIndex: "orderId",
			key: "orderId",
			align: "center",
			width: "15%"
		},
		{
			title: "商品封面",
			dataIndex: "iconId",
			key: "iconId",
			align: "center",
			ellipsis: {
				showTitle: false
			},
			width: "8%",
			className: "iconId_tableClass",
			render: (_: any, record: MyGoodsRateGetListItem) => (
				<Cimage src={record.goods.iconId[0].url} width={80} height={80}></Cimage>
			)
		},
		{
			title: "商品名称",
			dataIndex: "name",
			key: "name",
			align: "center",
			width: "15%",
			render: (_: any, record: MyGoodsRateGetListItem) => <>{record.goods.name}</>
		},
		{
			title: "买家头像",
			dataIndex: "avatar",
			key: "avatar",
			align: "center",
			ellipsis: {
				showTitle: false
			},
			width: "8%",
			className: "iconId_tableClass",
			render: (_: any, record: MyGoodsRateGetListItem) => <Cimage src={record.user.avatar} width={80} height={80}></Cimage>
		},
		{
			title: "买家昵称",
			dataIndex: "userName",
			key: "userName",
			align: "center",
			width: "15%",
			render: (_: any, record: MyGoodsRateGetListItem) => <>{record.user.userName || "未命名买家"}</>
		},
		{
			title: "评分",
			dataIndex: "count",
			key: "count",
			align: "center",
			width: "15%",
			render: (_: any, record: MyGoodsRateGetListItem) => <Rate disabled defaultValue={Number(record.count || 0)} />
		},
		{
			title: "内容",
			dataIndex: "description",
			key: "description",
			align: "center",
			width: "20%",
			ellipsis: {
				showTitle: false
			}
		},
		{
			title: "操作",
			align: "center",
			key: "action",
			width: "10%",
			render: (_: any, record: MyGoodsRateGetListItem) => (
				<>
					{record.reply && (
						<Popover
							placement="leftBottom"
							content={
								<>
									<div>{dayjs(record.reply.createTime).format("YYYY-MM-DD HH:mm")} :</div>
									<div>{record.reply.description}</div>
								</>
							}
							trigger="focus"
						>
							<Button>查看回复</Button>
						</Popover>
					)}
					{!record.reply && (
						<Popover
							placement="leftBottom"
							content={
								<>
									<div className="mb-10">回复评价：</div>
									<TextArea
										className="w-300"
										value={popoverDescription}
										autoSize={{ minRows: 3 }}
										placeholder="请输入回复内容"
										showCount={true}
										maxLength={200}
										allowClear={true}
										onChange={(e: any) => setPopoverDescription(e.target.value)}
									/>
									<Space className="mt-10">
										<Button onClick={() => setPopoverVisible(false)}>取消</Button>
										<Button type="primary" onClick={() => popoverSubmit(record)}>
											确定
										</Button>
									</Space>
								</>
							}
							trigger="click"
							open={popoverVisible}
							onOpenChange={handleOpenChange}
						>
							<Button type="primary">回复评论</Button>
						</Popover>
					)}
				</>
			)
		}
	];
	return (
		<div className="orderAdminComment">
			<Space align="end" className="flex items-center w-full justify-end mb-10">
				<Select
					allowClear
					placeholder="请选择筛选商品的订单"
					style={{ width: 300 }}
					onChange={handleSelectChange}
					optionLabelProp="label"
				>
					{goodsData.map(item => (
						<Option key={item.id} value={item.id} label={item.name}>
							<Image
								src={item.iconId[0]?.url}
								alt={item.name}
								style={{ width: 30, height: 30, marginRight: 10 }}
								preview={false}
							/>
							{item.name}
						</Option>
					))}
				</Select>
				<Button
					type="primary"
					icon={<RedoOutlined />}
					onClick={() => {
						getList(listQuery);
					}}
				>
					刷新
				</Button>
			</Space>
			<Table
				loading={loading}
				bordered={false}
				dataSource={tableData}
				columns={columns}
				rowKey={record => record.id}
				pagination={{
					current: listQuery.page, // 当前页码
					pageSize: listQuery.size, // 每页条数
					total: listQuery.total, // 数据总数
					showSizeChanger: true, // 显示每页条数切换器
					showQuickJumper: true // 显示快速跳转输入框
				}}
				onChange={pagination => handleTableChange(pagination)} // 分页变化回调
			/>
		</div>
	);
};
export default orderAdminComment;
